package com.cyh.forum.controller;

import com.cyh.forum.common.AppResult;
import com.cyh.forum.common.ResultCode;
import com.cyh.forum.config.AppConfig;
import com.cyh.forum.dao.UserMapper;
import com.cyh.forum.exception.ApplicationException;
import com.cyh.forum.model.User;
import com.cyh.forum.services.IUserService;
import com.cyh.forum.utils.MD5Util;
import com.cyh.forum.utils.StringUtil;
import com.cyh.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.annotation.Target;

//  对api接口进行说明
@Api(tags = "用户接口")
//  日志注解
@Slf4j
//  说明 这是一个返回数据的 Controller
@RestController
//  指定一级路径
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService iUserService;


    /**
     *  用户注册
     * @param username  用户名
     * @param nickname  用户昵称
     * @param password  用户密码
     * @param passwordRepeat    确认密码
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
//        //  非空校验
//        if (StringUtil.isEmpty(username)
//                ||StringUtil.isEmpty(password)
//                ||StringUtil.isEmpty(nickname)
//                ||StringUtil.isEmpty(passwordRepeat)){
//            // 返回错误信息
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }
        //  检验两次输入的密码是否一致
        if (!password.equals(passwordRepeat)){
            //  打印错误日志
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        //  准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //  对 密码 进行加密
        String salt = UUIDUtil.UUID_32();
        user.setPassword(MD5Util.md5Salt(password,salt));
        user.setSalt(salt);


        iUserService.createNormalUser(user);

        return  AppResult.success();
    }


    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("用户密码") @RequestParam("password") @NonNull String password){

        //  调用Service中的登录方法,返回User对象,并进行非空校验
        User user = iUserService.login(username,password);
        if (user == null){
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }

        //   如果登录成功,把User对象设置到Session作用域中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);

        return AppResult.success();
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,  /** 当用户不传id的时候,需要从session获取用户信息 */
                                       @ApiParam("用户id") @RequestParam(value = "id",required = false) Long id){ /** required = false表示该值为 非必传参数  */
        User user = null;
        if (id == null){
            // 1. 如果id为空,从session中获取当前登录用户信息
            HttpSession session = request.getSession(false); // session不存在时,不主动创建它
            //  判断 session和用户信息 是否有效
            if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null){
                //  用户没有登录,返回错误信息
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }
            //  从session中获取当前登录用户信息
            user = (User) session.getAttribute(AppConfig.USER_SESSION);

        }else {
            // 2. 如果id不为空,从数据库中 根据id 查找出用户信息
            user = iUserService.selectById(id);
        }

        //  判断 user对象 是否为空
        if (user == null){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        //  返回正常的结果
        return AppResult.success(user);
    }

    @ApiOperation(" 退出登录 ")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        //  获取session
        HttpSession session = request.getSession(false);
        //  校验session是否存在
        if (session != null){
            //  如果存在, 销毁session
            log.info(" 退出成功 ");
            session.invalidate();
        }

        return AppResult.success("退出成功");
    }

    @ApiOperation("修改用户个人中心信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                @ApiParam("电话") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark){
        //  非空校验
        if (StringUtil.isEmpty(username)
                && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark)
                && gender == null ){
            //  返回错误
            return AppResult.failed("请输入要修改的内容");
        }
        //  获取当前用户id
        val session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //  构造更新对象 user
        User update = new User();
        update.setId(user.getId());
        update.setUsername(username);
        update.setNickname(nickname);
        update.setGender(gender);
        update.setEmail(email);
        update.setPhoneNum(phoneNum);
        update.setRemark(remark);

        //  调用service层
        iUserService.modifyInfo(update);
        //  查询最新的用户信息
        user = iUserService.selectById(user.getId());
        //  把最新的用户信息设置到session中
        //session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //  校验新密码与确认密码是否相同
        if (!newPassword.equals(passwordRepeat)){
            //  返回错误
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
        }
        //  获取session中的user对象
        val session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //  调用service层
        iUserService.modifyPassword(user.getId(), newPassword,oldPassword);
        //  返回结果
        return AppResult.success();
    }

}
